#include "websocket.h"
#include <iostream>

WebSocketService::WebSocketService(int port) : port_(port) {
    server_.init_asio();
    
    server_.set_open_handler(std::bind(&WebSocketService::onOpen, this, std::placeholders::_1));
    server_.set_close_handler(std::bind(&WebSocketService::onClose, this, std::placeholders::_1));
    server_.set_message_handler(std::bind(&WebSocketService::onMessage, this, 
        std::placeholders::_1, std::placeholders::_2));
}

WebSocketService::~WebSocketService() {
    stop();
}

void WebSocketService::run() {
    server_.listen(port_);
    server_.start_accept();
    server_.run();
}

void WebSocketService::stop() {
    server_.stop();
}

void WebSocketService::setMessageHandler(MessageHandler handler) {
    messageHandler_ = handler;
}

void WebSocketService::send(websocketpp::connection_hdl hdl, const std::string& message) {
    try {
        server_.send(hdl, message, websocketpp::frame::opcode::text);
    } catch (const websocketpp::exception& e) {
        std::cerr << "WebSocket send failed: " << e.what() << std::endl;
    }
}

void WebSocketService::broadcast(const std::string& message) {
    for (const auto& conn : connections_) {
        auto con = server_.get_con_from_hdl(conn.first);
        send(con, message);
    }
}

void WebSocketService::onOpen(websocketpp::connection_hdl hdl) {
    auto con = server_.get_con_from_hdl(hdl);
    connections_[con.get()] = "";
    std::cout << "New connection established" << std::endl;
}

void WebSocketService::onClose(websocketpp::connection_hdl hdl) {
    auto con = server_.get_con_from_hdl(hdl);
    connections_.erase(con.get());
    std::cout << "Connection closed" << std::endl;
}

void WebSocketService::onMessage(websocketpp::connection_hdl hdl, MessagePtr msg) {
    if (messageHandler_) {
        messageHandler_(hdl, msg->get_payload());
    }
}